承上篇,.NET Core有提供許多的 Middleware給大家使用,但如果大家想要自訂義也是可以的!
今天來實作一個 LOG Middleware
那麼我們就開始吧!
實作如下
於目錄底下建立一個 Middleware資料夾,建立一個檔案命名為CustomerExceptionMiddleware.cs
using Serilog;
namespace web.Middleware
{
    public class CustomerExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        public CustomerExceptionMiddleware(RequestDelegate next, IServiceProvider serviceProvider)
        {
            _next = next;
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "錯誤訊息 => " + ex.Message);
                if (ex.InnerException != null)
                {
                    Log.Fatal(ex.InnerException, ex.InnerException.Message);
                }
            }
        }
    }
}
*這裡有用到套件Serilog,NuGet安裝Serilog、Serilog.Sinks.Console、Serilog.Sinks.File,之後再詳細說明使用方法。
由上圖可看到我們使用try-catch把next包起來,所以若是有任何的Exception都會被catch起來,留下Log。
接著,我們打開Program.cs,先在最上方加入LOG的設定
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.Console() //將Log輸出到終端機
    .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day) //將Log輸出為檔案,命名以當天日期為區分
    .CreateLogger();
我們把LOG Middleware放進Program.cs,要注意擺放的順序喔!(詳細可看上一篇)
測試
HomeController.cs
在Index()直接 throw new Exception();
結果
先拿掉Program.cs的 app.UseMiddleware();
在Action加上 [MiddlewareFilterAttribute]
建立Class,定義要加入的 Middleware
CustomerExceptionPipeline.cs
using web.Middleware;
namespace web.Pipeline
{
    public class CustomerExceptionPipeline
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseMiddleware<CustomerExceptionMiddleware>();
        }
    }
}
結果
那今天就到這邊囉,大家明天見!